package com.wxs.config;


import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /* ShiroFilterFactroyBean    第三步*/
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        /*设置安全管理器*/
        factoryBean.setSecurityManager(securityManager);

        /*添加内置过滤器*/
        /*
         * anno 无需认证就可以访问
         * authc: 必须认证才能访问
         * user:    必须拥有记住我功能才能使用
         * perms:    拥有对某个资源的权限才能访问
         * role:    拥有某个角色权限才能访问
        * */
        Map<String, String> filterMap = new LinkedHashMap<>();
        /*filterMap.put("/user/add","authc");
        filterMap.put("/user/update","authc");*/
        filterMap.put("/user/*","authc");

        factoryBean.setFilterChainDefinitionMap(filterMap);

        /*设置登录页面*/
        factoryBean.setLoginUrl("/toLogin");

        return factoryBean;
    }

    /* DafaultWebSecurityManager 第二步*/
    @Bean
    public DefaultWebSecurityManager securityManager (@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        /*关联userRealm*/
        securityManager.setRealm(userRealm);
        return  securityManager;
    }

    /*创建realm对象 第一步 需要自定义类userRealm*/
    @Bean(name = "userRealm")
    public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher){
        /*增加MD5加密*/
        UserRealm userRealm = new UserRealm();
        /*注入密码加密*/
        userRealm.setCredentialsMatcher(matcher);
        return userRealm;
    }


    /*密码加密算法设置*/
    @Bean(name = "hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        /*散列次数*/
        hashedCredentialsMatcher.setHashIterations(3);
        return hashedCredentialsMatcher;
    }

}
